<template>
    <div class="px-6">
        <el-form-item label="欢迎语" prop="welcome_introducer" label-width="60px">
            <el-input
                v-model="formData.welcome_text"
                placeholder=""
                type="textarea"
                :autosize="{ minRows: 8, maxRows: 8 }"
                clearable
                resize="none"
            />
            <div class="form-tips">
                打开聊天窗口后会主动发送，添加双井号可添加提问示例
            </div>
        </el-form-item>

        <el-form-item label="指令集" prop="instruction" label-width="60px">
            <div class="mb-2">
                <el-button type="primary" @click="handleInstUpdate(-1)">添加指令</el-button>
            </div>
            <el-table
                ref="tableRef"
                v-loading="pager.loading"
                :data="pager.lists"
                row-key="id"
            >
                <el-table-column label="关键词" prop="keyword" min-width="200" />
                <el-table-column label="附件" width="70">
                    <template #default="scope: { row: RobotInstructListResponse }">
                        <el-tag v-if="scope.row.annex.length > 0" type="primary">
                            {{ scope.row.annex.length }}
                        </el-tag>
                        <el-tag v-else type="info">
                            {{ scope.row.annex.length }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="类型" width="70">
                    <template #default="scope: { row: RobotInstructListResponse }">
                        <el-tag v-if="scope.row.scene === 'fixed'" type="info">固定</el-tag>
                        <el-tag v-if="scope.row.scene === 'direct'" type="info">指令</el-tag>

                    </template>
                </el-table-column>
                <el-table-column label="操作" width="110">
                    <template #default="{ $index }">
                        <el-button type="primary" link @click="handleInstUpdate($index)">查看</el-button>
                        <el-button type="danger" link @click="handleInstDelete($index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="w-full flex justify-end my-4 mb-0">
                <paging
                    v-model="pager"
                    layout="prev, pager, next"
                    size="small"
                    @change="queryLists"
                />
            </div>
        </el-form-item>

        <ClientOnly>
            <popup
                :show="visible"
                :async-close="false"
                :loading="loading"
                :title="instData.id ? '指令编辑' : '指令添加'"
                width="580px"
                @close="visible = false"
                @confirm="handleInstConfirm"
            >
                <el-form class="py-4 px-8">
                    <el-form-item label="场景" prop="scene" label-width="70">
                        <el-radio-group v-model="instData.scene">
                            <el-radio value="fixed">固定</el-radio>
                            <el-radio value="direct">指令</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="关键词" prop="keyword" label-width="70">
                        <el-input
                            v-model="instData.keyword"
                            placeholder="请输入关键词"
                            clearable
                            :maxlength="20"
                            :show-word-limit="true"
                        />
                    </el-form-item>
                    <el-form-item label="回复内容" prop="content" label-width="70">
                        <el-input
                            v-model="instData.content"
                            placeholder="请输入回复内容"
                            type="textarea"
                            :autosize="{ minRows: 8, maxRows: 8 }"
                            clearable
                            :maxlength="8000"
                            :show-word-limit="true"
                            resize="none"
                        />
                    </el-form-item>
                    <el-form-item label="附带图片" prop="images">
                        <upload-multiple
                            v-model:files="images"
                            type="image"
                            :limit="5"
                            list-type="picture-card"
                            multiple
                            show-file-list
                        >
                            <icon name="el-icon-Plus" :size="20" />
                        </upload-multiple>
                    </el-form-item>

                    <el-form-item label="附带文件" prop="files">
                        <div class="w-full">
                            <upload-single
                                type="*"
                                :disabled="files.length >= 2"
                                @success="uploadFile"
                            >
                                <el-button :disabled="files.length >= 2">
                                    上传文件
                                </el-button>
                            </upload-single>
                            <div class="flex flex-col gap-2 mt-3">
                                <div
                                    v-for="(item, index) in files"
                                    :key="index"
                                    class="flex items-center border rounded-md bg-lighter p-2 py-1.5"
                                >
                                    <div class="flex items-center flex-1">
                                        <el-image
                                            class="w-[18px] h-[18px] mr-2"
                                            :src="suffixUtil.findUnitIcon(item.name)"
                                        />

                                        <nuxt-link
                                            :external="true"
                                            :to="item.url"
                                            target="_blank"
                                            class="text-base cursor-pointer underline hover:text-tx-regular"
                                        >
                                            {{ item.name }}
                                        </nuxt-link>
                                    </div>
                                    <icon
                                        name="el-icon-Delete"
                                        class="hover:text-error cursor-pointer"
                                        @click="handleFileDelete(index)"
                                    />
                                </div>
                            </div>
                        </div>
                    </el-form-item>
                </el-form>
            </popup>
        </ClientOnly>
    </div>
</template>

<script setup lang="ts">
import {useVModel} from '@vueuse/core'
import suffixUtil from '~/utils/suffix'
import robotInstructApi from '~/api/agent/robot/instruct'

const props = defineProps<{
    modelValue: Record<string, any>
}>()

const emits = defineEmits<{
    (event: 'update:modelValue', value: Record<string, any>): void
}>()

const formData = useVModel(props, 'modelValue', emits)

// 指令附件
const files = ref<any[]>([])
const images = ref<any[]>([])

// 指令参数
const visible = ref<boolean>(false)
const loading = ref<boolean>(false)
const instData = reactive({
    id: 0,
    bot: formData.value.code,
    logo: '',
    scene: '',
    keyword: '',
    content: '',
    annex: [] as RobotInstructAnnex[]
})

// 查询参数
const queryParams = reactive({
    bot: ''
})

// 分页查询
const { pager, queryLists } = usePaging({
    fetchFun: robotInstructApi.lists,
    params: queryParams
})

/**
 * 指令保存
 */
const handleInstConfirm = async () => {
    const _images = images.value.map((item: any) => ({
        file_type: 'image',
        file_name: item.name,
        file_size: item.size,
        file_ext: item.ext,
        file_path: item.url
    }))

    const _files = files.value.map((item: any) => ({
        file_type: 'file',
        file_name: item.name,
        file_size: item.size,
        file_ext: item.ext,
        file_path: item.path
    }))

    instData.annex = [..._images, ..._files]

    loading.value = true
    if (instData.id) {
        await robotInstructApi.edit(instData)
            .then(async () => {
                visible.value = false
                await queryLists()
                feedback.msgSuccess('编辑成功')
            }).finally(() => {
                loading.value = false
            })
    } else {
        await robotInstructApi.add(instData)
            .then(async () => {
                visible.value = false
                await queryLists()
                feedback.msgSuccess('添加成功')
            }).finally(() => {
                loading.value = false
            })
    }
}

/**
 * 指令更新
 *
 * @param {number} index
 * @author zero
 */
const handleInstUpdate = async (index: number) => {
    instData.id = 0
    instData.scene = 'fixed'
    instData.keyword = ''
    instData.content = ''
    instData.annex = []
    images.value = []
    files.value = []

    if (index !== -1) {
        const data = pager.lists[index]
        instData.id = data.id
        instData.scene = data.scene
        instData.keyword = data.keyword
        instData.content = data.content
        instData.annex = data.annex
        data.annex.forEach((item: any) => {
            switch (item.file_type) {
                case 'image':
                    images.value.push({
                        name: item.file_name,
                        size: item.file_size,
                        ext: item.file_ext,
                        url: item.file_path
                    })
                    break
                case 'file':
                    files.value.push({
                        name: item.file_name,
                        size: item.file_size,
                        ext: item.file_ext,
                        url: item.file_path
                    })
                    break
            }
        })
    }

    visible.value = true
}

/**
 * 指令删除
 *
 * @param {number} index
 * @author zero
 */
const handleInstDelete = async (index: number) => {
    feedback.confirm('您确定要删除指令吗?').then(async () => {
        const data = pager.lists[index]
        await robotInstructApi.delete({
            id: data.id,
            bot: formData.value.code
        }).then(async () => {
            await queryLists()
            feedback.msgSuccess('删除成功')
        })
    })
}

/**
 * 文件删除
 *
 * @param {number} index
 * @author zero
 */
const handleFileDelete = async (index: number) => {
    files.value.splice(index, 1)
}

/**
 * 上传文件
 *
 * @param data
 * @author zero
 */
const uploadFile = (data: any) => {
    files.value.push({
        name: data.name,
        size: data.size,
        ext: data.ext,
        url: data.path
    })
}

watch(
    () => formData.value.code,
    async (val: any) => {
        if (val) {
            instData.bot = val
            queryParams.bot = val
            await queryLists()
        }
    }, { immediate: true }
)
</script>
